from django.shortcuts import redirect
import datetime
from django.utils.deprecation import MiddlewareMixin
from web import models
from django.conf import settings


class Tracer(object):
    def __init__(self):
        self.user = None
        self.price_policy = None
        self.project = None


class AutoMiddleWare(MiddlewareMixin):

    def process_request(self, request):
        request.tracer = Tracer()
        """如果用户一登陆，则request中赋值"""
        user_id = request.session.get("user_id", 0)
        user_object = models.UserInfo.objects.filter(id=user_id).first()
        request.tracer.user = user_object
        # request.tracer = tracer_object
        # 中间件加权限处理
        if request.path_info in settings.WHITE_LIST_URL:
            return
        if not request.tracer.user:
            return redirect("websass:login")

        # 登陆成功后之后，访问后台管理时，获取当前用户说拥有的额度
        # 方法一: 免费额度在交易记录表中存储
        # 获取当前用户ID值最大，最近的交易
        _object = models.Transaction.objects.filter(t_user=user_object, t_status=2).order_by('-id').first()
        # 判断是否过期
        time = datetime.datetime.now()
        if _object.t_end and _object.t_end < time:
            # 已过期，改为免费版
            _object = models.Transaction.objects.filter(t_user=user_object, t_status=2, t_price__category=1).first()
        # 没有过期
        # request.transaction = _object
        request.tracer.price_policy = _object.t_price
        # request.price_policy = tracer_object

        # 方式二：免费额度存储配置文件

        """
        _object = models.Transaction.objects.filter(t_user=user_object, t_status=2).order_by('-id').first()
        if not _object:
            # 没有购买
            request.price_policy = models.CommodityPrices.objects.filter(category=1, title="个人免费版").first()
        else:
            # 付费版
            time = datetime.datetime.now()
            if _object.t_end and _object.t_end < time:
                request.price_policy = models.CommodityPrices.objects.filter(category=1, title="个人免费版").first()
            else:
                request.price_policy = _object.t_price
        """

    def process_view(self, request, view, args, kwargs):
        if not request.path_info.startswith('/websass/manage/'):
            return
        project_id = kwargs.get("project_id")

        # 判读这个id是否是我创建的
        my_crate_project = models.Project.objects.filter(creator=request.tracer.user, id=project_id).first()
        if my_crate_project:
            request.tracer.project = my_crate_project
            return
        my_join_project = models.ProjectUser.objects.filter(user=request.tracer.user, project_id=project_id)
        if my_join_project:
            request.tracer.project = my_join_project.project
            return
        return redirect('websass:project_list')
